package com.hhx.baselibrary.net;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.hhx.baselibrary.R;

/**
 * Created by Administrator on 2018/12/5.
 */

public class LoadingDialogHandler extends Handler {

    public static final int SHOW_PROGRESS_DIALOG = 1;
    public static final int DISMISS_PROGRESS_DIALOG = 2;

    private Dialog mDialog;
    private Context mContext;
    private boolean cancelable;
    private ProgressCancelListener mProgressCancelListener;

    public LoadingDialogHandler(Context mContext, ProgressCancelListener mProgressCancelListener, boolean cancelable) {
        this.mContext = mContext;
        this.mProgressCancelListener = mProgressCancelListener;
        this.cancelable = cancelable;
    }

    private void initLoadingDialog() {
        if (mDialog == null) {
            View view = LayoutInflater.from(mContext).inflate(R.layout.dialog_loading, null);
            TextView loadingText = (TextView) view.findViewById(R.id.id_tv_loading_dialog_text);
            loadingText.setText("加载中...");

            mDialog = new Dialog(mContext, R.style.CustomProgressDialog);
            mDialog.setCancelable(cancelable);
            mDialog.setCanceledOnTouchOutside(false);
            mDialog.setContentView(view, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));

            if (cancelable) {
                mDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        mProgressCancelListener.onCancelProgress();
                    }
                });
            }
            if (!mDialog.isShowing() && mContext != null) {
                mDialog.show();
            }
        }
    }

    private void dismissLoadingDialog() {
        if (mDialog != null && mContext != null) {
            mDialog.dismiss();
            mDialog = null;
        }
    }

    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
            case SHOW_PROGRESS_DIALOG:
                initLoadingDialog();
                break;
            case DISMISS_PROGRESS_DIALOG:
                dismissLoadingDialog();
                break;
        }
    }
}
